package com.itheima.wechatweb;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVo;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.utils.RedisUtil;
import com.itheima.utils.SignatureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @outhor
 * @date 2020/2/5 14:51
 */

@RequestMapping("order")
@RestController
public class orderController {

    @Autowired
    private RedisUtil redisUtil;

    @Reference
    private OrderService orderService;

    @RequestMapping("submit")
    public Result submit (@RequestBody OrderInfoVo orderInfoVo){
        String sign = SignatureUtil.sign(orderInfoVo);

        Long setnx = redisUtil.setnx(sign, sign);
        if(setnx == 0L){//setnx=1 说明设置成功
            return new Result(false,"无效请求 setnx");
        }

        String validateCode = orderInfoVo.getValidateCode();
        String telephone = orderInfoVo.getTelephone();
        //1.校验验证码
        String redisCode = redisUtil.get(telephone + RedisConstant.SENDTYPE_ORDER);
        if (redisCode==null || !redisCode.equals(validateCode)){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
        if (orderInfoVo.getMemberId()!=null){
            Member member = orderService.getMemberById(orderInfoVo.getMemberId());
            orderInfoVo.setName(member.getName());
//            orderInfoVo.setIdCard(member.getIdCard());
            orderInfoVo.setTelephone(member.getPhoneNumber());
            orderInfoVo.setSex((member.getSex() == "男" ? 1: 2));
        }
        orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);
        //2.到service层中下单
        Result result = orderService.submit(orderInfoVo);
        if (result.isFlag()){
            //3.下单成功,给短信提示,目前阿里云本号没有权限
        }
        return result;
    }

    @RequestMapping("findById")
    public Result findById(String id){
        OrderInfoVo orderInfoVo = orderService.findById(id);
        return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,orderInfoVo);
    }
}
